import Big from 'big.js'
import { FieldType } from './constants'

export const plus = (num, ...rest) => new Big(num).plus(...rest)

export const times = (num, ...rest) => new Big(num).times(...rest)

/**
 * 判断值是否为空
 * @param {String|Number|Object|Array} value
 * @param {Boolean} allowBlank 允许空字符串
 */
export const isEmpty = (value, allowBlank) => value === null || value === undefined || (allowBlank ? false : value === '')

/**
 * 格式化语言
 * @param {String | Undefined} language 语言
 * @returns {String | Undefined} 格式化的语言
 */
export const normalizeLanguage = language => language && language.replace('_', '-').toLowerCase()

let supportsLocales
export const toLocaleStringSupportsLocales = () => {
  if (supportsLocales === undefined) {
    try {
      (0).toLocaleString('i')
      supportsLocales = false
    } catch (e) {
      supportsLocales = e.name === 'RangeError'
    }
  }
  return supportsLocales
}

/**
 * 获取格式化参数
 * @param {String} type 格式化类型 number/currency
 * @param {Object} options 格式化参数
 */
export const getNumberFormatOptions = (type, options) => {
  if (type === 'number') {
    return { style: 'decimal' }
  }
  if (options && options.currency) {
    return { style: 'currency' }
  }
  return { style: 'decimal', minimumFractionDigits: 2, maximumFractionDigits: 2 }
}

/**
 * 格式化金额或数字
 * @param {Number} value 格式化数据
 * @param {String} type number/currency
 * @param {Object} options 格式化参数
 */
export const toLocaleStringPolyfill = (value, type, options) => {
  if (type === FieldType.number) {
    const fraction = String(value).split('.')[1]
    return value.toLocaleString().split('.')[0] + (fraction ? `.${fraction}` : '')
  }
  const currency = options && options.currency
  return `${currency ? `${currency} ` : ''}${value.toLocaleString()}`
}

/**
 * 返回格式化数字
 * @param {Number|Number} num
 * @param {Number} digits
 */
export const toFixed = (num, digits) => {
  num = parseFloat(num)
  if (Number.isNaN(num)) {
    return ''
  }
  const value = new Big(num)
  return value.toFixed(digits)
}

/**
 * 格式化数字
 * @param {String | Number} value
 * @param {String} lang
 * @param {Object} options
 */
export const formatNumber = (value, lang, options) => {
  const v = parseFloat(value)
  if (!Number.isNaN(v)) {
    if (toLocaleStringSupportsLocales()) {
      return v.toLocaleString(normalizeLanguage(lang), {
        ...getNumberFormatOptions(FieldType.number, options),
        ...options
      })
    }
    return toLocaleStringPolyfill(v, FieldType.number, options)
  }
  return value
}
/**
 * 格式化金额
 * @param {String | Number} value
 * @param {String} lang
 * @param {Object} options
 */
export const formatCurrency = (value, lang, options) => {
  const v = parseFloat(value)
  let nextValue = value
  if (!Number.isNaN(v)) {
    if (toLocaleStringSupportsLocales()) {
      nextValue = v.toLocaleString(normalizeLanguage(lang), {
        ...getNumberFormatOptions(FieldType.currency, options),
        ...options
      })
    } else {
      nextValue = toLocaleStringPolyfill(v, FieldType.currency, options)
    }
  }
  const { precision } = options || {}
  return precision === 0 ? String(nextValue).split('.')[0] : nextValue
  // return value
}

/**
 * 格式比率
 * @param {Number} value
 */
export const formatRatio = value => {
  if (isEmpty(value)) return value
  return `${value}%`
}

/*
  * 判断obj是否为一个整数
  */
function isInteger (obj) {
  return Math.floor(obj) === obj
}
/*
  * 将一个浮点数转成整数，返回整数和倍数。如 3.14 >> 314，倍数是 100
  * @param floatNum {number} 小数
  * @return {object}
  *   {times:100, num: 314}
  */
function toInteger (floatNum) {
  const ret = { times: 1, num: 0 }
  if (isInteger(floatNum)) {
    ret.num = floatNum
    return ret
  }
  const strfi = floatNum + ''
  const dotPos = strfi.indexOf('.')
  const len = strfi.substr(dotPos + 1).length
  const times = Math.pow(10, len)
  const intNum = Number(floatNum.toString().replace('.', ''))
  ret.times = times
  ret.num = intNum
  return ret
}
/*
  * 核心方法，实现加减乘除运算，确保不丢失精度
  * 思路：把小数放大为整数（乘），进行算术运算，再缩小为小数（除）
  *
  * @param a {number} 运算数1
  * @param b {number} 运算数2
  * @param op {string} 运算类型，有加减乘除（add/subtract/multiply/divide）
  * @param digit {string} 保留小数位
  *
  */
function operation (a, b, digit, op) {
  const o1 = toInteger(a)
  const o2 = toInteger(b)
  const n1 = o1.num
  const n2 = o2.num
  const t1 = o1.times
  const t2 = o2.times
  const max = t1 > t2 ? t1 : t2
  let result = null
  switch (op) {
    case 'add':
      if (t1 === t2) { // 两个小数位数相同
        result = n1 + n2
      } else if (t1 > t2) { // o1 小数位 大于 o2
        result = n1 + n2 * (t1 / t2)
      } else { // o1 小数位 小于 o2
        result = n1 * (t2 / t1) + n2
      }
      result = result / max
      break
    case 'subtract':
      if (t1 === t2) {
        result = n1 - n2
      } else if (t1 > t2) {
        result = n1 - n2 * (t1 / t2)
      } else {
        result = n1 * (t2 / t1) - n2
      }
      result = result / max
      break
    case 'multiply':
      result = (n1 * n2) / (t1 * t2)
      break
    default:
      result = (n1 / n2) * (t2 / t1)
  }
  console.log(result, digit)
  if (typeof digit === 'number') {
    return toFixed(result, digit)
  } else {
    return result
  }
}
// 加减乘除的四个接口
export function add (a, b, digit) {
  return operation(a, b, digit, 'add')
}
export function subtract (a, b, digit) {
  return operation(a, b, digit, 'subtract')
}
export function multiply (a, b, digit) {
  return operation(a, b, digit, 'multiply')
}
export function divide (a, b, digit) {
  return operation(a, b, digit, 'divide')
}

export default Big
